<?php
@opcache_reset();
define('LOGPATH', dirname(__FILE__));
include_once "wxBizMsgCrypt.php";

//以下三个变量，自己去开放平台上管理中心根据实际情况填写。
$config = include "./config.php";
$encodingAesKey = $config['encodingAesKey']; 
$token = $config['token'];
$component_appid = $config['component_appid'];
$component_appsecret = $config['component_appsecret'];

//验证Token
checkSignature($token);

$act = isset($_GET['act'])?trim($_GET['act']):"";
if($act=="call"){//授权回调地址
	$authorization_code  = isset($_GET["auth_code"])?trim($_GET["auth_code"]):"";
	//使用授权码换取公众号或小程序的接口调用凭据和授权信息
	$ComponentVerifyTicket =  file_get_contents("/data/wwwroot/redpack/wx/ticket.log");
	$result  = get_component_access_token ($component_appid, $component_appsecret, $ComponentVerifyTicket );	
        $url = "https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=".@$result['component_access_token'];
	$data = '{"component_appid":"' . $component_appid . '","authorization_code":"' . $authorization_code . '"}';
	$res = curl_post($data, $url);	
	$data2 = json_decode ( $res,true);	
	if(@$data2['authorization_info']['authorizer_refresh_token']){
		$authorizer_refresh_token = @$data2['authorization_info']['authorizer_refresh_token'];
	    echo "授权成功,获取预约授权码为：".$authorizer_refresh_token;
		file_put_contents(LOGPATH.'/authorizer_refresh_token.log', $authorizer_refresh_token);		
	    exit();
	}else{
		exit('回调失败!!!');
	}	
}elseif($act=='preAuthCode'){ //获取预授权码
    $redirect_uri = "http://{$config['api_domain']}/wx/wx1.php?act=call";
    $pre_auth_code = pre_auth_code($component_appid,$component_appsecret); 
	if($pre_auth_code){
		$string = "component_appid={$component_appid}&pre_auth_code={$pre_auth_code}&redirect_uri={$redirect_uri}";
		$jumpUrl = "http://{$config['api_domain']}/wx/pre_auth_code.php?{$string}";
		header("location:{$jumpUrl}");
		exit();
	}else{
		exit("获取预授权码失败");
	}
}

$timeStamp  = empty($_GET['timestamp'])?"":trim($_GET['timestamp']);
$nonce      = empty($_GET['nonce'])?"":trim($_GET['nonce']);
$msg_sign   = empty($_GET['msg_signature'])?"":trim($_GET['msg_signature']);
$encryptMsg = file_get_contents('php://input');
if(!$encryptMsg){exit("500");}
$pc = new WXBizMsgCrypt($token, $encodingAesKey, $component_appid);

$xml_tree = new DOMDocument();
$xml_tree->loadXML($encryptMsg);
$array_e = $xml_tree->getElementsByTagName('Encrypt');
$encrypt = $array_e->item(0)->nodeValue;

//==================={component_verify_ticket->component_access_token->pre_auth_code}
$format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
$from_xml = sprintf($format, $encrypt);
logResult('/form.log', $from_xml);
// 第三方收到公众号平台发送的消息
$msg = '';
$errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg);
if ($errCode == 0) {
    //print("解密后: " . $msg . "\n");
    $xml = new DOMDocument();
    $xml->loadXML($msg);
    $array_e = $xml->getElementsByTagName('ComponentVerifyTicket');
    $component_verify_ticket = $array_e->item(0)->nodeValue;
	/**
	*获取component_verify_ticket
	*/
    file_put_contents(LOGPATH.'/ticket.log', $component_verify_ticket);
	file_put_contents(LOGPATH.'/component_appid.log', $component_appid);
	file_put_contents(LOGPATH.'/component_appsecret.log', $component_appsecret);
    logResult('/msgmsg.log','解密后的component_verify_ticket是：'.$component_verify_ticket);
    echo 'success';
} else {
    logResult('/error.log','解密后失败：'.$errCode);
    print($errCode . "\n");
}

//获取component_access_token
function get_component_access_token($component_appid,$component_appsecret,$component_verify_ticket){	
	$url = "https://api.weixin.qq.com/cgi-bin/component/api_component_token";
	$data = array(
				"component_appid"=>$component_appid,
				"component_appsecret"=>$component_appsecret,
				"component_verify_ticket"=>$component_verify_ticket
			);
	$send_result = https_request($url, json_encode($data));
	$send_result = json_decode($send_result,true);	
	return $send_result;
}
//换取pre_auth_code
function pre_auth_code($component_appid,$component_appsecret){
	$ComponentVerifyTicket =  file_get_contents("/data/wwwroot/redpack/wx/ticket.log");
	if(!$component_appid&&$component_appsecret&&$ComponentVerifyTicket){
		exit(500);
	}	
	$result = get_component_access_token($component_appid,$component_appsecret,$ComponentVerifyTicket);
	$token = @$result['component_access_token'];
    $url = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token={$token}";
    $data = array(
            "component_appid"=>$component_appid
    );
$send_result = https_request($url, json_encode($data));
$send_result = json_decode($send_result,true);
return @$send_result['pre_auth_code'];
}
//验证签名
function checkSignature($token){
	//获得参数 signature nonce token timestamp echostr
	$nonce     = isset($_GET['nonce'])?trim($_GET['nonce']):"";
	$timestamp = isset($_GET['timestamp'])?trim($_GET['timestamp']):"";
	$echostr   = isset($_GET['echostr'])?trim($_GET['echostr']):"";
	$signature = isset($_GET['signature'])?trim($_GET['signature']):"";
	//形成数组，然后按字典序排序
	$array = array();
	$array = array($nonce, $timestamp, $token);
	sort($array);
	//拼接成字符串,sha1加密 ，然后与signature进行校验
	$str = sha1( implode( $array ) );
	if( $str == $signature && $echostr ){
		//第一次接入weixin api接口的时候
		echo  $echostr;
		exit;
	}
}
//日志记录
function logResult($path,$data){
    file_put_contents(LOGPATH.$path, '['.date('Y-m-d : h:i:sa',time()).']'.$data."\r\n",FILE_APPEND);
}
function https_request($url,$data=null){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
        if(!empty($data)){
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
}
function curl_post($data, $url) {
	$curl = curl_init ();
	curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
	curl_setopt ( $curl, CURLOPT_TIMEOUT, 500 );
	curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false );
	curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, false );
	curl_setopt ( $curl, CURLOPT_URL, $url );
	curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, "POST" );
	curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
	$res = curl_exec ( $curl );
	curl_close ( $curl );
	return $res;
}
?>